<template>
  <!-- 新增满减/送 -->
  <div>
    <div style="display: flex; justify-content: space-between">
      <el-button type="primary" @click="dialogAddGift = true">
        新增满减/送
      </el-button>
      <el-button @click="$emit('send')">返回</el-button>
    </div>
    <!-- 礼包信息展示列表 -->
    <div style="margin-top: 10px">
      <el-table :data="giftList" :empty-text="emptyText">
        <el-table-column label="条件金额" prop="prepaid_amount" />
        <el-table-column label="开始时间" prop="activity_start_at" />
        <el-table-column label="结束时间" prop="activity_end_at" />
        <el-table-column label="礼包数量" prop="gift_stock" />
        <el-table-column label="礼包描述" prop="gift_desc" />
        <el-table-column align="left" label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click="delStop(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="display: flex; justify-content: space-between">
        <div></div>
        <el-pagination
          :current-page.sync="page"
          layout="prev, pager, next, jumper"
          :total="total"
          @current-change="getGiftInfo"
        />
      </div>
    </div>
    <!-- 新增礼包对话框 -->
    <el-dialog title="添加满减/送" :visible.sync="dialogAddGift">
      <div>
        <!-- 选择充值卡 -->
        <div class="flex_y_center" style="margin-bottom: 20px">
          <div class="inp_title">
            <span>*</span>
            充值卡：
          </div>
          <el-select
            v-model="giftForm.prepaid_id"
            clearable
            placeholder="请选择需绑定该礼包的充值卡"
            @change="chooseCard"
            @focus="getRecharge"
          >
            <el-option
              v-for="(item, index) of rechargeList"
              :key="index"
              :label="item.prepaid_name"
              :value="item.id"
            />
          </el-select>
        </div>
        <!-- 条件金额 -->
        <div class="flex_y_center" style="margin-bottom: 20px">
          <div class="inp_title">
            <span>*</span>
            条件金额：
          </div>
          <el-input
            v-model="giftForm.prepaid_amount"
            placeholder="请输入条件金额"
            style="width: 25%"
          />
        </div>
        <!-- 开始，结束时间 -->
        <div class="flex_y_center" style="margin-bottom: 20px">
          <div class="inp_title">
            <span>*</span>
            活动起止时间：
          </div>
          <el-date-picker
            v-model="giftForm.activity_start_at"
            placeholder="选择活动开始日期"
            type="date"
            value-format="yyyy-MM-dd"
          />
          <div style="margin: 0 5px">至</div>
          <el-date-picker
            v-model="giftForm.activity_end_at"
            placeholder="选择活动结束日期"
            type="date"
            value-format="yyyy-MM-dd"
          />
        </div>
        <!-- 礼包数量 -->
        <div class="flex_y_center" style="margin-bottom: 20px">
          <div class="inp_title">
            <span>*</span>
            礼包数量：
          </div>
          <el-input
            v-model="giftForm.gift_stock"
            placeholder="请输入礼包数量"
            style="width: 25%"
          >
            <template slot="append">件</template>
          </el-input>
        </div>
        <!-- 领取限制 -->
        <div style="margin-bottom: 20px; display: flex">
          <div class="inp_title">
            <span>*</span>
            用户领取限制：
          </div>
          <!-- 单选 -->
          <div>
            <el-radio-group
              v-model="giftForm.receive_type"
              style="
                display: flex;
                flex-direction: column;
                justify-content: space-between;
              "
              @change="giftForm.limit_count = ''"
            >
              <el-radio label="unlimited">无限制</el-radio>
              <el-radio label="new_customer" style="margin: 10px 0">
                仅新课
              </el-radio>
              <el-radio label="limit_count">限领</el-radio>
            </el-radio-group>
            <div style="height: 5px"></div>
            <!-- 赠送金 -->
            <el-input
              v-model="giftForm.limit_count"
              :disabled="giftForm.receive_type != 'limit_count'"
              style="width: 50%"
            >
              <template slot="append">件</template>
            </el-input>
          </div>
        </div>
        <!-- 礼包备注 -->
        <div class="flex_y_center" style="margin-bottom: 20px">
          <div class="inp_title">
            <span>*</span>
            礼包备注：
          </div>
          <el-input
            v-model="giftForm.gift_desc"
            maxlength="100"
            placeholder="请输入礼包备注，最多100字"
            show-word-limit
            style="width: 40%"
            type="textarea"
          />
        </div>
        <!-- 礼包内容 -->
        <div v-show="isGift == 'Y'" style="display: flex">
          <div class="inp_title" style="position: relative; top: 10px">
            <span>*</span>
            礼包内容：
          </div>
          <div>
            <!-- 多选 -->
            <div
              style="
                display: flex;
                flex-direction: column;
                justify-content: space-between;
              "
            >
              <div
                v-for="(item, index) of contentList"
                :key="index"
                class="flex_y_center"
                style="margin-bottom: 10px"
              >
                <el-checkbox
                  v-model="item.check"
                  :label="item.name"
                  style="margin-right: 10px"
                  @change="selectContent(item, index)"
                />
                <el-input
                  v-show="index == 0 || index == 1"
                  v-model="prepaid_type[index].prepaid_gift_value"
                  :disabled="item.inpBool"
                />
                <el-select
                  v-show="index == 2"
                  v-model="prepaid_type[index].prepaid_gift_value"
                  clearable
                  :disabled="item.inpBool"
                  filterable
                  remote
                  :remote-method="getGoods"
                  @focus="getGoods"
                >
                  <el-option
                    v-for="(itemChild, indexChild) of item.options"
                    :key="indexChild"
                    :label="
                      itemChild.goods_name + ' - ' + itemChild.goods_attr_name
                    "
                    :value="itemChild.goods_attr_id"
                  />
                </el-select>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="searchForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getPrepaidList,
    getGiftList,
    addGift,
    delprepaidGif,
  } from '@/api/storedValue'
  import { getGoodsList } from '@/api/public'

  export default {
    data() {
      return {
        giftList: [], // 存放礼包列表
        page: 1,
        total: 10,

        emptyText: ' ',
        rechargeList: [], // 存放充值卡列表
        dialogAddGift: false, // 控制新增礼包对话框显示隐藏
        isGift: '', // 是否有礼包
        contentList: [
          { name: '赠送金', label: 'gift_amount', inpBool: true, check: false },
          { name: '折扣', label: 'gift_discount', inpBool: true, check: false },
          {
            name: '赠品',
            label: 'gift_goods',
            inpBool: true,
            check: false,
            options: [],
          },
        ],
        // 礼包内容
        prepaid_type: [
          { prepaid_gift_type: '', prepaid_gift_value: '' },
          { prepaid_gift_type: '', prepaid_gift_value: '' },
          { prepaid_gift_type: '', prepaid_gift_value: '' },
        ],
        // 作为添加礼包的传递参数
        giftForm: {
          prepaid_id: '', // 选择的充值卡id
          prepaid_amount: '', // 充值条件金额
          activity_start_at: '', // 活动开始时间
          activity_end_at: '', // 活动结束时间
          gift_stock: '', // 礼包数量
          receive_type: '', // 领取类型
          limit_count: '', // 领取限制次数
          gift_desc: '', // 礼包备注
          prepaid_type: [], // 礼包内容
        },
        hint: {
          prepaid_id: '选择的充值卡id',
          prepaid_amount: '充值条件金额',
          activity_start_at: '活动开始时间',
          activity_end_at: '活动结束时间',
          gift_stock: '礼包数量',
          gift_desc: '礼包备注',
        },
      }
    },
    watch: {
      // 当对话框关闭，将 giftForm 中的属性值全部初始化为空
      dialogAddGift(newValue) {
        if (!newValue) {
          this.initForm()
        }
      },
    },
    mounted() {
      this.getGiftInfo()
    },
    methods: {
      // 初始化form
      initForm() {
        this.rechargeList = []
        this.isGift = ''
        this.prepaid_type = [
          { prepaid_gift_type: '', prepaid_gift_value: '' },
          { prepaid_gift_type: '', prepaid_gift_value: '' },
          { prepaid_gift_type: '', prepaid_gift_value: '' },
        ]

        for (let item in this.giftForm) {
          item == 'prepaid_type'
            ? (this.giftForm[item] = [])
            : (this.giftForm[item] = '')
        }
        for (let item of this.contentList) {
          item.inpBool = true
          item.check = false
          if (this.contentList.options) {
            this.contentList.options = []
          }
        }
      },
      // 获取充值卡列表
      getRecharge() {
        if (this.rechargeList.length == 0) {
          const params = {
            prepaid_type: 'stored',
          }
          getPrepaidList(params).then((res) => {
            this.rechargeList = res.data
          })
        }
      },
      // 获取商品
      getGoods(keyWord) {
        const params = {
          goods_name: typeof keyWord == 'object' ? '' : keyWord,
          goods_type: 'all',
        }
        getGoodsList(params).then((res) => {
          this.contentList[2].options = []
          for (let item of res.data) {
            if (item.type_code != 'curriculum') {
              this.contentList[2].options.push(item)
            }
          }
        })
      },
      // 选择充值卡，判断该卡是否可以赠送礼包
      chooseCard() {
        this.isGift = ''
        for (let item of this.rechargeList) {
          if (item.id == this.giftForm.prepaid_id) {
            this.isGift = item.is_gift
          }
        }
      },
      // 获取礼包列表
      getGiftInfo() {
        const loading = this.$loading({
          lock: true,
          target:
            this.giftList.length == 0
              ? '.el-table__empty-block'
              : '.el-table__body',
        })
        getGiftList().then((res) => {
          this.giftList = res.data
          loading.close()
          if (res.data.length == 0) {
            this.emptyText = '暂无数据'
          }
        })
      },
      selectContent(item, index) {
        item.inpBool = !item.inpBool
        if (item.inpBool) {
          this.prepaid_type[index].prepaid_gift_value = ''
          this.prepaid_type[index].prepaid_gift_type = ''
        } else {
          this.prepaid_type[index].prepaid_gift_type = item.label
        }
      },
      // 检索form数据是否有遗漏
      searchForm() {
        for (let i = 0; i < this.contentList.length; i++) {
          if (this.contentList[i].check) {
            this.giftForm.prepaid_type.push(this.prepaid_type[i])
          }
        }

        for (let item in this.hint) {
          if (this.giftForm[item] == '') {
            this.$message.error(this.hint[item] + '未填写')
            return
          }
        }
        if (this.isGift == 'Y' && this.giftForm.prepaid_type.length == 0) {
          this.$message.error('填写礼包值')
          return
        }
        if (
          this.giftForm.receive_type == 'limit_count' &&
          this.giftForm.limit_count == ''
        ) {
          return
        }

        this.addGit()
      },
      // 添加礼包
      addGit() {
        if (this.giftForm.prepaid_type.length != 0) {
          this.giftForm.prepaid_type = JSON.stringify(
            this.giftForm.prepaid_type
          )
        }
        const params = this.giftForm
        addGift(params).then(() => {
          this.dialogAddGift = false
          this.getGiftInfo()
        })
      },
      // 删除礼包
      delStop(id) {
        this.$confirm('确定要将选中的礼包删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            const params = {
              id,
            }
            delprepaidGif(params).then(() => {
              this.$message.success('删除成功')
              this.getGiftInfo()
            })
          })
          .catch(() => {
            return
          })
      },
    },
  }
</script>

<style scoped>
  .inp_title {
    width: 25%;
    text-align: right;
  }
  span {
    color: red;
  }
</style>
